//
//  NRWCarMorePictureToShareVC.m
//  New_Runway
//
//  Created by 张记 on 2018/5/29.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarMorePictureToShareVC.h"
#import "AddPictureCell.h"
#import "NRWCarChoosePictureCell.h"
#import "NRWCarListsModel.h"
#import "CarBaseInfoModel.h"
#import "NRWCarShareTemplateManager.h"
#import "NRWCarSharePictureBottomView.h"
#import "NRWCarPhotoManager.h"
#import "RITLPhotos.h"
#import <Photos/Photos.h>
#import "NRWTemplateAlertView.h"
#import "NRWCarUrlShortModel.h"
#import "NRWCarPhotoManager.h"
@interface NRWCarMorePictureToShareVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,RITLPhotosViewControllerDelegate,NRWTemplateAlertViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionview;
@property (nonatomic, strong) CarBaseInfoModel *infomodel;
@property (nonatomic, strong) NSMutableArray *imageModelArray;
@property (nonatomic, strong) NRWCarSharePictureBottomView *bottom;
@property (nonatomic, strong) NSMutableArray *selectdImageArray;
//@property (nonatomic, assign) CGSize assetSize;
@property (nonatomic, copy) NSArray <UIImage *> * assets;
@property (nonatomic, copy) NSArray <NSString *> *saveAssetIds;
@property (nonatomic, copy) NSString *shortUrl;
@end

@implementation NRWCarMorePictureToShareVC
-(NSMutableArray *)imageModelArray{
    if (!_imageModelArray) {
        _imageModelArray = [[NSMutableArray alloc] init];
    }
    return _imageModelArray;
}
-(NSMutableArray *)selectdImageArray{
    if (!_selectdImageArray) {
        _selectdImageArray = [[NSMutableArray alloc] init];
    }
    return _selectdImageArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"多图分享";
    [self.navigationBarView.rightItem setTitle:@"去分享" forState:UIControlStateNormal];
    self.view.backgroundColor = kColorWhite();
    [self creatCollectionView];
//    _assetSize =  CGSizeMake((Screen_width - 40) / 3, (Screen_width - 40) / 3);
    if (self.dataArray.count == 1) {
        Result *rt = self.dataArray[0];
        [self loadCarBaseInfo:rt];
        [self loadShortUrl];
    }else{
        NSMutableArray *images = [NSMutableArray array];
        for (Result *rt in self.dataArray) {
            NSString *urlStr = [NSString stringWithFormat:@"%@%@",ImageApi,rt.carImageUrl];
            [images addObject:urlStr];
        }
        [SVProgressHUD show];
        [NRWCarShareTemplateManager downloadImageWithImageUrlArray:images carBaseModelS:self.dataArray completed:^(NSArray<UIImage *> *imageModelArr) {
            [self.imageModelArray addObjectsFromArray:imageModelArr];
            if (self.imageModelArray.count >= 5) {
                [self.imageModelArray insertObject:self.imageModel atIndex:4];
            }else{
                [self.imageModelArray addObject:self.imageModel];
            }
            
            [SVProgressHUD dismiss];
            [self.collectionview reloadData];
            
        } completed1:^(NSArray<UIImage *> *imageArray) {
            [self.selectdImageArray addObjectsFromArray:imageArray];
            if (self.selectdImageArray.count >= 5) {
                [self.selectdImageArray insertObject:self.imageModel atIndex:4];
            }else{
                [self.selectdImageArray addObject:self.imageModel];
            }
            self.bottom.imageS = self.selectdImageArray;
        }];
    }
    
}

-(void)creatCollectionView{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing      = 5;
    layout.minimumInteritemSpacing = 5;
    _collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.navH, Screen_width, Screen_height  - self.BotH - self.navH - 50) collectionViewLayout:layout];
    _collectionview.backgroundColor = UIColorHex(0xf5f5f5);
    _collectionview.delegate=self;
    _collectionview.dataSource=self;
    [_collectionview registerNib:[UINib nibWithNibName:@"NRWCarChoosePictureCell" bundle:nil] forCellWithReuseIdentifier:@"NRWCarChoosePictureCell"];
    [self.view addSubview:_collectionview];
    self.bottom = [[[NSBundle mainBundle] loadNibNamed:@"NRWCarSharePictureBottomView" owner:self options:nil]firstObject];
    self.bottom.nav = self.navigationController;
    self.bottom.carCount = self.dataArray.count;
    self.bottom.frame = CGRectMake(0, Screen_height - self.BotH - 50, Screen_width, self.BotH + 50);
    [self.view addSubview:self.bottom];
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.imageModelArray.count + 1;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NRWCarChoosePictureCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"NRWCarChoosePictureCell" forIndexPath:indexPath];
    if (indexPath.row == self.imageModelArray.count) {
        cell.chooseBtn.hidden = YES;
        cell.mainImage.image = [UIImage imageNamed:@"share_add"];
        return cell;
    }
    NRWCarSharePictureModel *model = self.imageModelArray[indexPath.row];
    cell.chooseBtn.hidden = NO;
    cell.index = indexPath;
    cell.imageModel = model;
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((Screen_width - 40) / 3, (Screen_width - 40) / 3);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section

{
    return UIEdgeInsetsMake(10, 10, 0, 10);//分别为上、左、下、右
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.imageModelArray.count) {
        [self editPeopleMessage];
        return;
    }
    NSMutableArray *imageArray = [NSMutableArray array];
    for ( NRWCarSharePictureModel *model in self.imageModelArray) {
        [imageArray addObject:model.picture];
    }
    [HUPhotoBrowser showFromImageView:nil withImages:imageArray atIndex:indexPath.row];

}


-(void)loadCarBaseInfo:(Result *)model{
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,carDetailApi] refreshRequest:YES cache:NO params:@{@"carId":model.carId,@"imageViewId":@(3)} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        _infomodel = [CarBaseInfoModel mj_objectWithKeyValues:response];
        
        if (_infomodel.code == 1) {
            NSMutableArray *iamges = [NSMutableArray array];
            for (NSDictionary *dic in _infomodel.result.carImages) {
                CarCarimages *imagemodel =  [CarCarimages mj_objectWithKeyValues:dic];
                NSString *urlStr = [NSString stringWithFormat:@"%@%@",ImageApi,imagemodel.imageUrl];
                [iamges addObject:urlStr];
            }
            
            [NRWCarShareTemplateManager downloadImageWithImageUrlArray:iamges carBaseModelS:self.dataArray completed:^(NSArray<UIImage *> *imageModelArr) {
                [self.imageModelArray addObjectsFromArray:imageModelArr];
                if (self.imageModelArray.count >= 5) {
                    [self.imageModelArray insertObject:self.imageModel atIndex:4];
                }else{
                    [self.imageModelArray addObject:self.imageModel];
                }
                [SVProgressHUD dismiss];
                [self.collectionview reloadData];
            } completed1:^(NSArray<UIImage *> *imageArray) {
                [self.selectdImageArray addObjectsFromArray:imageArray];
                if (self.selectdImageArray.count >= 5) {
                    [self.selectdImageArray insertObject:self.imageModel atIndex:4];
                }else{
                    [self.selectdImageArray addObject:self.imageModel];
                }
                self.bottom.imageS = self.selectdImageArray;
            }];
            
        }

    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
        
    }];
    
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    
    NSIndexPath *index = userInfo[@"index"];
    NRWCarChoosePictureCell *cell = (NRWCarChoosePictureCell *)[self.collectionview cellForItemAtIndexPath:index];
    NRWCarSharePictureModel *model = self.imageModelArray[index.row];
    
    if (model.isSelected == YES) {
        model.isSelected = NO;
        [cell.chooseBtn setImage:[UIImage imageNamed:@"share_selected_no"] forState:UIControlStateNormal];
        [self.selectdImageArray removeObject:model];
    }else{
        if (self.selectdImageArray.count >= 9) {
            [ShowMessage showHintMessage:@"最多分享9张图片" duration:2 withRemindId:remindWarning];
        }else{
            model.isSelected = YES;
            [self.selectdImageArray addObject:model];
            [cell.chooseBtn setImage:[UIImage imageNamed:@"share_selected_yes"] forState:UIControlStateNormal];
        }
    }
    self.bottom.imageS = self.selectdImageArray;

}

- (UIImage *)downloadImage:(NSString *)imageUrl {
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", ImageApi, imageUrl]];
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    UIImage *img;
    if ([manager diskImageExistsForURL:url]) {
        img =  [[manager imageCache] imageFromDiskCacheForKey:url.absoluteString];
    } else {//从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        img = [UIImage imageWithData:data];
    }
    return img;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - RITLPhotosViewControllerDelegate
// 选中资源的本地标志位 用于记录
- (void)photosViewController:(UIViewController *)viewController
            assetIdentifiers:(NSArray <NSString *> *)identifiers
{
    self.saveAssetIds = identifiers;
}

//选中规定尺寸缩略图
- (void)photosViewController:(UIViewController *)viewController
             thumbnailImages:(NSArray <UIImage *> *)thumbnailImages
{

}

//原图
- (void)photosViewController:(UIViewController *)viewController
                      images:(NSArray <UIImage *> *)images
{
//    获得原比例的图片
    [SVProgressHUD show];
    dispatch_queue_t queue = dispatch_queue_create("com.nrw.image", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        
        for (UIImage *image in images) {
            NRWCarSharePictureModel *model = [[NRWCarSharePictureModel alloc] init];
            model.isSelected = NO;
            model.isTemplate = NO;
            model.isMark = YES;
            model.imageType = 3;
            model.picture = [UIImage imageWithData:[UIImage compressImage:image maxSize:1000 maxFileSize:300]];
            if (self.dataArray.count == 1) {
                Result *rt = self.dataArray[0];
                model.CarModel = rt;
            }
            [self.imageModelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [self.collectionview reloadData];
        });
    });
    
}
-(void)editPeopleMessage{
    
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
                
            case 0: //相机
                [self choosePictureType:YES];
                
                break;
            case 1: //相册
                
                [self choosePictureType:NO];
                
                break;
            case 2:
                return;
                break;
        }
    }
    else {
        switch (buttonIndex) {
            case 0:
                [self choosePictureType:NO];
                
                break;
            case 1:
                return;
                break;
        }
    }
    
}
-(void)choosePictureType:(BOOL)isCamre{
    if (isCamre == YES) {
        kSelfWeak;
        [[NRWCarPhotoManager shareInstance] presentPicker:PickerType_Camera photoCut:PhotoCutType_YES target:self callBackBlock:^(UIImage *image, BOOL isCancel) {
            if (image) {
                NRWCarSharePictureModel *model = [[NRWCarSharePictureModel alloc] init];
                model.isSelected = NO;
                model.isTemplate = NO;
                model.isMark = YES;
                model.imageType = 3;
                model.picture = [UIImage imageWithData:[UIImage compressImage:image maxSize:1000 maxFileSize:300]];
                [weakSelf.imageModelArray addObject:model];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.collectionview reloadData];
                });
            }
        }];
        
    }else{
        
        RITLPhotosViewController *photoController = RITLPhotosViewController.photosViewController;
        photoController.configuration.maxCount = 9;//最大的选择数目
        photoController.configuration.containVideo = false;//选择类型，目前只选择图片不选择视频
        photoController.photo_delegate = self;
        //        photoController.thumbnailSize = self.assetSize;//缩略图的尺寸
        //        photoController.defaultIdentifers = self.saveAssetIds;//记录已经选择过的资源
        [self presentViewController:photoController animated:true completion:^{}];
    }
}
-(void)rightItemClick{
  
    if (self.selectdImageArray.count == 0) {
        [ShowMessage showHintMessage:@"请选择车辆图片" duration:2.0 withRemindId:remindWarning];
        return;
    }
    
    NRWTemplateAlertView *alertView = [[NRWTemplateAlertView alloc] init];
    alertView.delegate = self;
    [alertView show];
    Result *carModel = self.dataArray.firstObject;
    alertView.contentText = [NRWCarShareTemplateManager getShareTextWithCarTitle:carModel.carTitle carPrice:carModel.carRetailPrice carLicenceDate:carModel.carLicenceDate carLicenceState:carModel.carLicenceState carMileage:carModel.carMileage shortUrl:_shortUrl carCount:self.dataArray.count];
}

- (void)loadShortUrl {
    
        if (self.dataArray.count == 1) {
            Result *model = self.dataArray.firstObject;
            NSString *long_url = [NSString stringWithFormat:@"%@/mshop/src/cars_share.html?marketId=%@&shopId=%@&imgUrl=%@&customerShopId=false&carId=%@&os=false&shareUserName=%@&shareUserMobile=%@", Api, model.marketId, model.shopId, ImageApi, model.carId,[NRWCarUser sharedUser].userName,[NRWCarUser sharedUser].userMobile];
            NSString *encodeUrl = [long_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [self loadShortLink:encodeUrl];
            
        }
}

-(void)loadShortLink:(NSString *)url{
    
    [YQNetworking postWithUrl:@"http://api.t.sina.com.cn/short_url/shorten.json" refreshRequest:YES cache:NO params:@{@"source":@"3271760578",@"url_long":url} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        NSArray *array = response;
        if (array.count > 0) {
            NSDictionary *dic = array[0];
            NRWCarUrlShortModel *model = [NRWCarUrlShortModel mj_objectWithKeyValues:dic];
            _shortUrl = model.url_short;
          
        }
        
    } failBlock:^(NSError *error) {
        
    }];
}
#pragma mark - NRWTemplateAlertViewDelegate
- (void)templateAlertView:(NRWTemplateAlertView *)view copyDidClick:(UIButton *)sender {
    
    [view dismiss];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = view.contentText;
    [self showShareViewController];
}

- (void)templateAlertView:(NRWTemplateAlertView *)view notCopyDidClick:(UIButton *)sender {
    
    [view dismiss];
    [self showShareViewController];
}

- (void)templateAlertView:(NRWTemplateAlertView *)view closeBtnDidClick:(UIButton *)sender {
    
    [view dismiss];
}
#pragma mark - 展示分享弹框
- (void)showShareViewController {
    NSMutableArray *imageArray = [NSMutableArray array];
    for (NRWCarSharePictureModel *model in self.selectdImageArray) {
        NSData *data = [UIImage compressImage:model.picture maxFileSize:300];
        [imageArray addObject:data];
    }
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:imageArray applicationActivities:nil];
    NSMutableArray *arrM = @[UIActivityTypePostToFacebook,
                             UIActivityTypePostToTwitter,
                             UIActivityTypePostToWeibo,
                             UIActivityTypeMessage,
                             UIActivityTypeMail,
                             UIActivityTypePrint,
                             UIActivityTypeCopyToPasteboard,
                             UIActivityTypeAssignToContact,
                             UIActivityTypeSaveToCameraRoll,
                             UIActivityTypeAddToReadingList,
                             UIActivityTypePostToFlickr,
                             UIActivityTypePostToVimeo,
                             UIActivityTypePostToTencentWeibo,
                             UIActivityTypeAirDrop].mutableCopy;
    if (@available(iOS 9.0, *)) {
        [arrM addObject:UIActivityTypeOpenInIBooks];
    }
    
    if (@available(iOS 11.0, *)) {
        [arrM addObject:UIActivityTypeMarkupAsPDF];
    }
    
    activityVC.excludedActivityTypes = arrM.copy;
    [self presentViewController:activityVC animated:YES completion:nil];
}
-(void)dealloc{
    
}


@end
